﻿using System.Windows.Input;
using Windows.UI.Xaml;

namespace Sumc.Client.ModernUI.Attachements
{
    public static class Behaviours
    {
        public static ICommand GetPointerPressed(DependencyObject obj)
        {
            return (ICommand)obj.GetValue(PointerPressedProperty);
        }

        public static void SetPointerPressed(DependencyObject obj, ICommand value)
        {
            obj.SetValue(PointerPressedProperty, value);
        }

        public static readonly DependencyProperty PointerPressedProperty =
            DependencyProperty.RegisterAttached("PointerPressed", typeof(ICommand), typeof(Behaviours), new PropertyMetadata(null, SubscribeToPointerPressedEvent));

        public static object GetPointerPressedParameter(DependencyObject obj)
        {
            return obj.GetValue(PointerPressedParameterProperty);
        }

        public static void SetPointerPressedParameter(DependencyObject obj, object value)
        {
            obj.SetValue(PointerPressedParameterProperty, value);
        }

        public static readonly DependencyProperty PointerPressedParameterProperty =
            DependencyProperty.RegisterAttached("PointerPressedParameter", typeof(object), typeof(Behaviours), new PropertyMetadata(null));

        private static void SubscribeToPointerPressedEvent(DependencyObject d, DependencyPropertyChangedEventArgs args)
        {
            var sender = d as UIElement;
            if (sender != null)
            {
                sender.Tapped += ExecuteCommand;
            }
        }

        private static void ExecuteCommand(object sender, object e)
        {
            var element = sender as UIElement;
            var command = element.GetValue(PointerPressedProperty) as ICommand;
            if (command != null)
            {
                var commandParameter = element.GetValue(PointerPressedParameterProperty);
                if (command.CanExecute(commandParameter))
                {
                    command.Execute(commandParameter);
                }
            }
        }
    }
}
